﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Resources;

namespace PhoobearLibs.Resource.Resx
{
    public class ResxFile : ResourceFile<string>
    {

#region Constructor

        /// <summary>
        /// 생성자 
        /// </summary>
        public ResxFile()
        {

        }

        /// <summary>
        /// 생성자 
        /// </summary>
        /// <param name="path">경로</param>
        public ResxFile(string path)
        {
            this.Path = path;
        }

#endregion        

#region Protected Function
        
        /// <summary>
        /// 파일이 resx 파일인지 확인합니다.
        /// </summary>
        /// <param name="path">경로</param>
        /// <returns>파일이 정상이면 true 아니면 false</returns>
        protected override bool IsCorrectExtension(string path)
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            return fi.Extension.Equals(".resx", StringComparison.InvariantCultureIgnoreCase);
        }

        /// <summary>
        /// 데이터를 로드함
        /// </summary>
        /// <param name="path">경로</param>
        /// <returns>로드된 데이터</returns>
        protected override Dictionary<string, string> LoadData(string path)
        {
            Dictionary<string, string> collection = new Dictionary<string, string>();

            using (ResXResourceReader reader = new ResXResourceReader(path))
            {
                IDictionaryEnumerator enums = reader.GetEnumerator();
                while (enums.MoveNext())
                {
                    string id = enums.Key.ToString().Trim();
                    string value = enums.Value.ToString().Trim();

                    collection.Add(id, value);
                }
            }

            return collection;
        }

        /// <summary>
        /// 데이터 저장
        /// </summary>
        /// <param name="path">경로</param>
        /// <returns>파일이 정상적으로 저장되었는지 여부</returns>
        protected override bool SaveData(string path)
        {
            try
            {
                //쓰기             
                using (ResXResourceWriter resxWriter = new ResXResourceWriter(path))
                {
                    //기존 내용 반영
                    foreach (var item in this.Data)
                    {
                        resxWriter.AddResource(item.Key.ToString(), item.Value.ToString());                        
                    }
                }

                return true;
            }
            catch (System.Exception ex)
            {
                this.OnError(ex);
            }

            return false;
        }

#endregion
    
    }
}
